package com.imist.servlet;

import com.imist.domain.User;
import com.imist.utils.UploadUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RegistServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    //数据的接受：
    // 文件上传的基本操作
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //定义一个list集合，用于保存兴趣爱好的数据
            List<String > hobbyList = new ArrayList<String>();
            //定义一个Map集合用于保存接收到的数据
            Map<String ,String> map = new HashMap<String, String>();

            //1.创建一个磁盘文件项工厂对象
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //2.创建一个核心解析类
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            //3.解析request请求，返回的是list集合，集合中存放的是FileItem对象
            List<FileItem> list = servletFileUpload.parseRequest(request);

            //4.遍历集合获得每个fileitem ，判断是表单项是文件上传项
            String url = null;
            for (FileItem fileItem : list) {
                //判断是表单项还是文件上传项
                if (fileItem.isFormField()){
                    //普通表单项
                    String name = fileItem.getFieldName();//获取表单项的name属性的值
                    String value = fileItem.getString("utf-8");//获得表单项的value的值
                    System.out.println(name + "---"+ value);
                    //接收复选框的数据
                    if ("hobby".equalsIgnoreCase(name)){

                        String hobbyValue = fileItem.getString("utf-8");
                        //接收到一个值 ，将其放入到hobbylist集合的值
                        hobbyList.add(hobbyValue);
                        hobbyValue = hobbyList.toString().substring(1,hobbyList.toString().length()-1);
                        System.out.println(hobbyValue);
                        //将爱好的集合存入到Map集合中
                        map.put(name,hobbyValue);
                    }else {
                        //将数据存入到map集合
                        map.put(name,value);
                    }

                }else {

                    //文件上传项 ，实现文件上传的功能
                    //获得文件上传的名称
                    String filename = fileItem.getName();
                   if (!"".equals(filename)){
                       String uuidFileName = UploadUtils.getUUIDFileName(filename);
                       InputStream is = fileItem.getInputStream();
                       //可以上传到服务器，也可以上传到磁盘
                       String path = this.getServletContext().getRealPath("/upload");
                       System.out.println("realPath -->"+path);
                       //将输入流对接到输出流；
                       url = path+"/"+uuidFileName;
                       OutputStream os = new FileOutputStream(url);
                       int len = 0;
                       byte[] b = new byte[1024];
                       while((len = is.read(b)) != -1){
                           os.write(b,0,len);
                       }
                       is.close();
                       os.close();
                   }
                }
            }
            System.out.println("map:"+map.toString());
            //获得ServletContext对象
            List<User> users = (List<User>) this.getServletContext().getAttribute("list");
            //校验用户名
            for (User user : users) {
                if (user.getUsername().equals(map.get("username"))){
                    request.setAttribute("msg","用户名已经存在");
                    request.getRequestDispatcher("regist.jsp").forward(request,response);
                    return;
                }
            }
            //封装数据到User当中
            User user = new User();
            user.setUsername(map.get("username"));
            user.setPassword(map.get("password"));
            user.setNickname(map.get("nickname"));
            user.setSex(map.get("sex"));
            user.setHobby(map.get("hobby"));
            user.setPath(url);
            //将注册用户的信息存入到List集合中
            users.add(user);
            this.getServletContext().setAttribute("list",users);
            //注册成功跳转到登录页面
            request.getSession().setAttribute("username",user.getUsername());
            //获取项目路径项的页面，然后重定向
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }
}
